<template>
  <div class="flex justify-between text-[#e54c5f]">
    <router-link
      class="flex items-center cursor-pointer"
      to="/merchantSettings/permissions"
    >
      <el-icon><ArrowLeftBold /></el-icon>
      <span class="pl-5">{{
        route.query.type == "add" ? $t("创建身份") : $t("编辑身份")
      }}</span>
    </router-link>
  </div>
  <el-card class="my-5">
    <el-skeleton :rows="5" animated :loading="loading">
      <div class="w-72">
      <h3 class="py-5 text-xl">{{$t('身份名称')}}</h3>
        <el-input
          v-model="form.name"
          :placeholder="$t('设置身份名称')"
          clearable
          size="large"
        />
      </div>
      <h3 class="py-5 text-xl">{{$t('权限设置')}}</h3>
      <!-- 权限选择 -->
      <el-row :gutter="20" class="pb-5">
        <el-col :span="6"><span class="text-lg">{{$t('模块')}}</span></el-col>
        <el-col :span="18"><span class="text-lg">{{$t('操作')}}</span></el-col>
      </el-row>
      <el-row :gutter="20" class="pb-3" v-for="(item, index) in permissions">
        <el-col :span="6">
          <el-checkbox
            :indeterminate="itemIndeterminate(item)"
            @change="(val) => handleCheckAllChange(val, item)"
            v-model="item.checkedAll"
            >{{ item.class_name }}</el-checkbox
          >
        </el-col>
        <el-col :span="18">
          <el-checkbox-group v-model="checkbox" @change="handleCheckedChange">
            <el-checkbox
              v-for="class_value in item.class_value"
              :key="class_value.key"
              :label="class_value"
              >{{ class_value.value }}</el-checkbox
            >
          </el-checkbox-group>
        </el-col>
      </el-row>
      <!-- {{$t('merchantSettings.编辑')}} -->
      <el-button
        type="primary" :icon="SuccessFilled"
        size="large"
        class="w-48 mt-5"
        @click="handleSumbit"
        >{{route.query.type == "add" ? $t('提交') : $t('编辑')}}</el-button>
    </el-skeleton>
  </el-card>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { SuccessFilled } from '@element-plus/icons-vue'
import {
  addPermissionsGroupApi,
  permissionsApi,
  permissionsInfoGroupApi,
  updatePermissionsGroupApi,
} from "@/api/merchant/index";

const route = useRoute();
const router = useRouter();
let checkboxData = [];
let checkbox = ref([]);
const permissions = reactive([]);
const cypermissions = reactive([]);
const loading = ref(false);
const form = reactive({
  name: "",
  permissions_keys: "",
});

onMounted(async () => {
  if (route.query.id) {
    try {
      handleAllSelect(route.query.id);
    } catch (e) {}
  }
  if (route.query.type == "add") {
    getPermissionsApi();
  }
});

const handleAllSelect = async (id) => {
  try {
    loading.value = true;
    const res = await permissionsInfoGroupApi({ id: id });
    const newPermission = res.permission;
    const check = [];

    newPermission.forEach((item) => {
      // console.log(item);
      let newClass_value = item.class_value.filter((v) => {
        return v.selected;
      });
      if (newClass_value.length == item.class_value.length) {
        item.checkedAll = true;
      } else {
        item.checkedAll = false;
      }
    });
    if (res.permission.length) {
      res.permission.forEach((item) => {
        item.class_value.forEach((v) => {
          if (v.selected == 1) {
            check.push(v);
          }
        });
      });
    }
    checkbox.value = check;
    Object.assign(permissions, newPermission);
    Object.assign(cypermissions, newPermission);
    Object.assign(form, { name: res.name });
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

// 全选
const handleCheckAllChange = (val, item) => {
  const filterArr = checkbox.value.filter((v) => {
    return item.class_value.indexOf(v) == -1;
  });
  checkbox.value = val ? filterArr.concat(item.class_value) : filterArr;

};
// 中间状态
const itemIndeterminate = (item) => {
  return (
    item.class_value.some((v) => checkbox.value.indexOf(v) > -1) &&
    !item.class_value.every((v) => checkbox.value.indexOf(v) > -1)
  );
};
// 单个选择
const handleCheckedChange = (value) => {
  permissions.forEach((item) => {
    item.checkedAll = true;
    item.class_value.forEach((v) => {
      if (!checkbox.value.includes(v)) {
        item.checkedAll = false;
      }
    });
  });
};

const filterselectPermissionsData = () => {
  const arr = cypermissions
    .map((v) => ({
      class_name: v.class_name,
      class_key: v.class_key,
      class_value: v.class_value.filter((v) => checkbox.value.indexOf(v) > -1),
    }))
    .filter((v) => v.class_value.length);
  const keyarr = [];
  arr.forEach((item) => {
    keyarr.push(`web_${item.class_key}|${item.class_key}`);

    if (item.class_value.length) {
      item.class_value.forEach((action) => {
        keyarr.push(`web_${action.key}|${action.key}`);
      });
    }
  });

  return keyarr;
};

// 提交
const handleSumbit = async () => {
  try {
    if (!form.name) {
      return ElMessage({
        message: "请输入身份名称",
        type: "error",
        grouping: true,
      });
    }
    // filterselectPermissionsData()
    form.permissions_keys = filterselectPermissionsData().join(",");
    if (!form.permissions_keys) {
      return ElMessage({
        message: "请至少选择一项权限",
        type: "error",
        grouping: true,
      });
    }
    if (route.query.type == "add") {
      const res = await addPermissionsGroupApi(form);
      // console.log(res);
      ElMessage({
        message: "创建身份成功",
        type: "success",
        grouping: true,
      });
    }
    if (route.query.type == "edit") {
      const res = await updatePermissionsGroupApi({
        id: route.query.id,
        name: form.name,
        permissions_keys:filterselectPermissionsData().join(",")
      });
      ElMessage({
        message: "修改身份成功",
        type: "success",
        grouping: true,
      });
    }

    router.replace(`/merchantSettings/permissions`);
  } catch (error) {}
};
const getPermissionsApi = async () => {
  try {
    loading.value = true;
    const res = await permissionsApi();
    // console.log(res)
    // const data = JSON.parse(JSON.stringify(res.data.permissions));
    Object.assign(permissions, res);
    Object.assign(cypermissions, res);
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
// Promise.all([getPermissionsApi()]);
</script>
